require( "glon" )


--[[

	GModRP - Real Garry's Mod Roleplay.
			By Slob187.
		

]]		


function GMRP.RPSteamID( p )

	return p:UniqueID()
	
end	


function GMRP.GetInventoryLocation( p )

	return "GModRP/inventory1/"..GMRP.RPSteamID( p )..".txt"
	
end	
	

function GMRP.Inventory( p )
	
	local ILoc = GMRP.GetInventoryLocation( p )
	
	if !file.Exists( ILoc ) then return end	

	local decoded = glon.decode( file.Read( ILoc ) )	
	
	return decoded
	
end	


function GMRP.SendInventory( p )

	local ILoc = GMRP.GetInventoryLocation( p )
	
	if !file.Exists( ILoc ) then print( "Inventory file doesn't exist !" ) return end	

	p:SendLua( "MyInventory = {}" )

	local Inv = GMRP.Inventory( p )

	for k, v in pairs( Inv ) do
	
		p:SendLua( "MyInventory['" ..k.. "'] = "..v ) --SendLua ftw
		
	end	
	
end		
	
	
function GMRP.AddToInentory( p, theitem )

	if GMRP.Items[theitem] != nil then
	
		local ILoc = GMRP.GetInventoryLocation( p )		
		
		if file.Exists( ILoc ) then	
		
			local decoded = GMRP.Inventory( p )		
			
			if ( tonumber( decoded[theitem] ) != nil ) then
			
				decoded[theitem] = decoded[theitem] + 1
				
			else
			
				decoded[theitem] = 1
				
			end
			
			file.Write( ILoc, glon.encode( decoded ) )
			
		else
		
			local Inventory	= {}			
			
			Inventory[theitem] = 1
			
			file.Write( ILoc, glon.encode( Inventory ) )
			
		end
		
		GMRP.SendInventory( p )
		
	end
	
end	


function GMRP.TakeFromInventory( p, theitem )

	local ILoc = GMRP.GetInventoryLocation( p )		
	
	if !file.Exists( ILoc ) then return print( "Inventory file doesn't exist !" ) end
	
	local decoded = GMRP.Inventory( p )		

	if decoded[theitem] != nil then
	
		if decoded[theitem] > 1 then
		
			decoded[theitem] = decoded[theitem] - 1
			
		else
		
			decoded[theitem] = nil
			
		end
		
		file.Write( ILoc, glon.encode( decoded ) )
		
		GMRP.SendInventory( p )

	end	

end


function GMRP.DropItem( p, c, a )

	for itemname, item in pairs( GMRP.Items ) do
	
		for k, v in pairs( GMRP.Inventory( p ) ) do
		
			if k == itemname && k == a[1] then
			
				if GMRP.UseLimit( p ) then
				
					item.Spawn( p )
					GMRP.TakeFromInventory( p, a[1] )
					
				end	
				
			end
			
		end
		
	end	

end

GMRP.command( "inventory_drop", GMRP.DropItem )


function GMRP.InventoryUse( p, c, a )

	for itemname, item in pairs( GMRP.Items ) do
	
		for k, v in pairs( GMRP.Inventory( p ) ) do
		
			if k == itemname && k == a[1] then
			
				if GMRP.UseLimit( p ) then
				
					if item.Remove then
					
						item.Use( p )
						GMRP.TakeFromInventory( p, a[1] )
						
					end
					
					p.NextInventoryUse = CurTime() + 3
					
				end
				
			end
			
		end
		
	end	
	
end	

GMRP.command( "inventory_use", GMRP.InventoryUse )